<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { addFillTemplate, updateFillTemplate } from '@/service/api';
import { $t } from '@/locales';

defineOptions({
  name: 'TemplateOperateDrawer'
});

interface Props {
  operateType: 'add' | 'edit';
  rowData?: Api.Dataplatform.FillTemplate | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<'add' | 'edit', string> = {
    add: $t('page.dataplatform.fill.addTemplate'),
    edit: $t('page.dataplatform.fill.editTemplate')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.Dataplatform.FillTemplateEdit,
  'name' | 'code' | 'description' | 'targetTable' | 'status' | 'version' | 'projectId' | 'remark'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: '',
    code: '',
    description: '',
    targetTable: '',
    status: 1,
    version: '1.0',
    projectId: undefined,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'code' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
  status: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const api = props.operateType === 'add' ? addFillTemplate : updateFillTemplate;
  const data: Api.Dataplatform.FillTemplateEdit = {
    ...model
  };

  if (props.operateType === 'edit' && props.rowData) {
    data.id = props.rowData.id;
  }

  const { error } = await api(data);
  if (!error) {
    window.$message?.success(
      props.operateType === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess')
    );
    closeDrawer();
    emit('success');
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="640">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
        <NFormItem :label="$t('page.dataplatform.fill.templateName')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.dataplatform.fill.templateNamePlaceholder')" />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.fill.templateCode')" path="code">
          <NInput
            v-model:value="model.code"
            :placeholder="$t('page.dataplatform.fill.templateCodePlaceholder')"
            :disabled="operateType === 'edit'"
          />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.fill.description')" path="description">
          <NInput
            v-model:value="model.description"
            type="textarea"
            :placeholder="$t('page.dataplatform.fill.descriptionPlaceholder')"
            :rows="3"
          />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.fill.targetTable')" path="targetTable">
          <NInput v-model:value="model.targetTable" :placeholder="$t('page.dataplatform.fill.targetTablePlaceholder')" />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.fill.version')" path="version">
          <NInput v-model:value="model.version" :placeholder="$t('page.dataplatform.fill.versionPlaceholder')" />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.common.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio :value="1">{{ $t('page.dataplatform.common.enabled') }}</NRadio>
            <NRadio :value="0">{{ $t('page.dataplatform.common.disabled') }}</NRadio>
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.common.remark')" path="remark">
          <NInput
            v-model:value="model.remark"
            type="textarea"
            :placeholder="$t('page.dataplatform.common.remarkPlaceholder')"
            :rows="2"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
